#include "Http.hpp"

#define WWWROOT "./wwwroot"
std::string RequestStr(const HttpRequest& req){
    std::stringstream ss;
    ss << req._method << " " << req._path << " " <<req._version << "\r\n";
    for (auto& x : req._params){
        ss << x.first << "=" << x.second << "\r\n";
    }
    for (auto& x : req._headers){
        ss << x.first << ": " << x.second << "\r\n";
    }
    ss << "\r\n";
    ss << req._body;
    return ss.str();
}
void Hello(const HttpRequest& req,HttpResponse& rsp){
    rsp.SetContent(RequestStr(req),"text/plain");
    // sleep(15); //超时时间为10s,用来测试任务处理时间太长，对其他连接的影响。
}
void Post(const HttpRequest& req,HttpResponse& rsp){
    rsp.SetContent(RequestStr(req),"text/plain");
}
void Delete(const HttpRequest& req,HttpResponse& rsp){
    rsp.SetContent(RequestStr(req),"text/plain");
}
void Put(const HttpRequest& req,HttpResponse& rsp){
    std::string pathname = WWWROOT + req._path; //wwwroot/1234.txt
    DBG_LOG("file path: %s",pathname.c_str());
    Util::WriteFile(pathname,req._body);
}
int main()
{
    HttpServer server(8080);
    server.SetBaseDir(WWWROOT);
    server.SetThreadCount(3);
    server.Get("/hello",Hello);
    server.Post("/login",Post);
    server.Delete("/delete",Delete);
    server.Put("/1234.txt",Put);
    server.Listen();
    return 0;
}